const address = require("address");
const { machineIdSync } = require("node-machine-id");
const crypto = require('crypto');

/**
 * @description: 获取当前系统 IP 地址
 * @return {String}
 */
function addressIp() {
    return address.ip();
}

/**
 * @description: 获取当前系统 IPV6 地址
 * @return {String}
 */
function addressIpv6() {
    return address.ipv6();
}

/**
 * @description: 获取当前系统 MAC 地址
 * @return {String}
 */
function addressMac() {
    return new Promise((resolve) => {
        address.mac(function (err, addr) {
            if (err) {
                resolve(err);
            } else {
                resolve(addr);
            }
        });
    });
}

/**
 * @description: 获取当前系统 IP、IPV6、MAC 地址
 * @return {Object}
 */
function addressAll() {
    return new Promise((resolve) => {
        address.mac(function (err, mac) {
            if (err) {
                resolve({ ip: address.ip(), ipv6: address.ipv6(), mac: err });
            } else {
                resolve({ ip: address.ip(), ipv6: address.ipv6(), mac });
            }
        });
    });
}

const getMachineId = () => {
    const rawId = machineIdSync({ original: true });
    return crypto.createHash('md5').update(rawId).digest('hex');
}

/**
 * @description: address 方法重写
 * @return {Object}
 */
const _address = {
    ip: addressIp,
    ipv6: addressIpv6,
    mac: addressMac,
    all: addressAll,
    machineId: getMachineId(), // 客户端唯一id
};


module.exports = {
    address: _address,
};
